<template>
  <div>
    <!-- 搜索以及操作 -->
    <x-search>
      <template #search>
        <p>
          班级名称
          <a-input
            v-model:value="name"
            placeholder="请输入班级名称"
            style="width: 150px"
          />
        </p>
        <p style="margin-left: 20px">
          专业
          <a-select
            v-model:value="program_id"
            placeholder="请选择专业"
            style="width: 150px"
          >
            <a-select-option
              v-for="(value, index) in allPrograms"
              :key="index"
              :value="value.id"
              >{{ value.name }}</a-select-option
            >
          </a-select>
        </p>
        <p style="margin-left: 20px">
          状态
          <a-select
            v-model:value="status"
            placeholder="请选择状态"
            style="width: 150px"
          >
            <a-select-option value="0">启用</a-select-option>
            <a-select-option value="1">禁用</a-select-option>
          </a-select>
        </p>
        <a-button type="primary" style="margin-left: 10px" @click="but_search"
          >搜索</a-button
        >
        <a-button style="margin-left: 10px" @click="reset_search"
          >重置</a-button
        >
      </template>
      <template #operate>
        <a-button
          type="primary"
          style="margin-left: 10px"
          @click="showModal"
          v-checkpermission:foo.bar="'class_add'"
          ><template #icon><plus-outlined style="margin-right: 0" /></template
          >新增班级</a-button
        >
      </template>
    </x-search>

    <!-- 新增班级对话框 -->
    <a-modal v-model:open="open" title="新增班级" @ok="handleOk">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="班级名称" name="name">
          <a-input
            v-model:value="formState.name"
            placeholder="请输入班级名称"
          />
        </a-form-item>
        <a-form-item label="班级编号" name="class_id">
          <a-input
            v-model:value="formState.class_id"
            placeholder="请输入班级编号"
          />
        </a-form-item>
        <a-form-item label="所属专业" name="program_id">
          <a-select
            v-model:value="formState.program_id"
            placeholder="请选择专业"
            show-search
            option-filter-prop="label"
          >
            <a-select-option
              v-for="(value, index) in allPrograms"
              :key="index"
              :value="value.id"
              :label="value.name"
              >{{ value.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 班级列表表格 -->
    <a-table
      :dataSource="dataSource"
      :columns="columns"
      :loading="loading"
      :pagination="{
        pageSize: state.pageSize,
        total: state.total,
        current: state.current,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50'],
        showTotal: (total) => `共 ${total} 条`,
      }"
      @change="handleTableChange"
      :scroll="{ y: 600 }"
      v-checkpermission:foo.bar="'class_list'"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'state'">
          <a-tag :color="record.state === 0 ? 'green' : 'red'">
            {{ record.state === 0 ? "启用" : "禁用" }}
          </a-tag>
        </template>
        <template v-if="column.key === 'teacher_name'">
          <a-tag v-if="!record.teacher_name" color="error"> 暂无分配 </a-tag>
          {{ record.teacher_name }}
        </template>
        <template v-else-if="column.key === 'student_count'">
          <a @click="showStudentsModal(record.id)">{{
            record.student_count
          }}</a>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <!-- 编辑按钮 -->
            <a-tooltip title="查看班级学生" placement="top">
              <a-button
                type="text"
                size="small"
                @click="showStudentsModal(record.id)"
                v-checkpermission:foo.bar="'class_list'"
              >
                <template #icon>
                  <EditOutlined style="color: #1890ff; margin: 0" />
                </template>
                <span style="margin-left: 4px; color: #1890ff">查看</span>
              </a-button>
            </a-tooltip>
            <!-- 编辑按钮 -->
            <a-tooltip title="编辑" placement="top">
              <a-button
                type="text"
                size="small"
                @click="showModal_edit(record.id)"
                v-checkpermission:foo.bar="'class_edit'"
              >
                <template #icon>
                  <EditOutlined style="color: #1890ff; margin: 0" />
                </template>
                <span style="margin-left: 4px; color: #1890ff">编辑</span>
              </a-button>
            </a-tooltip>

            <!-- 分配老师 -->
            <a-tooltip title="班级分配老师" placement="top">
              <a-button
                type="text"
                size="small"
                @click="showModal_set(record)"
                v-checkpermission:foo.bar="'class_edit'"
              >
                <template #icon>
                  <EditOutlined style="color: #1890ff; margin: 0" />
                </template>
                <span style="margin-left: 4px; color: #1890ff">分配 </span>
              </a-button>
            </a-tooltip>

            <!-- 状态切换按钮 -->
            <a-tooltip
              :title="record.state === 0 ? '禁用' : '启用'"
              placement="top"
            >
              <a-button
                type="text"
                size="small"
                danger
                @click="
                  record.state === 0
                    ? disableClass(record.id)
                    : enableClass(record.id)
                "
                v-checkpermission:foo.bar="'class_delete'"
              >
                <template #icon>
                  <DeleteOutlined
                    style="margin: 0"
                    :style="{
                      color: record.state === 0 ? '#ff4d4f' : '#52c41a',
                    }"
                  />
                </template>
                <span
                  :style="{
                    color: record.state === 0 ? '#ff4d4f' : '#52c41a',
                  }"
                  >{{ record.state === 0 ? "禁用" : "启用" }}</span
                >
              </a-button>
            </a-tooltip>

            <!-- 删除按钮（仅当状态为禁用时显示） -->
            <a-tooltip v-if="record.state === 1" title="删除" placement="top">
              <a-button
                type="text"
                size="small"
                danger
                @click="deleteClass(record.id)"
                v-checkpermission:foo.bar="'class_delete'"
              >
                <template #icon>
                  <DeleteOutlined style="color: #cf1322" />
                </template>
                <span style="margin-left: 4px; color: #cf1322">删除</span>
              </a-button>
            </a-tooltip>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 编辑班级对话框 -->
    <a-modal v-model:open="open_edit" title="修改班级" @ok="handleOk_edit">
      <a-form
        ref="formRef_edit"
        :model="formState_edit"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="班级名称" name="name">
          <a-input v-model:value="formState_edit.name" />
        </a-form-item>
        <a-form-item label="班级编号" name="class_id">
          <a-input v-model:value="formState_edit.class_id" />
        </a-form-item>
        <a-form-item label="所属专业" name="program_id">
          <a-select
            v-model:value="formState_edit.program_id"
            placeholder="请选择专业"
            show-search
            option-filter-prop="label"
          >
            <a-select-option
              v-for="(value, index) in allPrograms"
              :key="index"
              :value="value.id"
              :label="value.name"
              >{{ value.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 班级学生列表对话框 -->
    <a-modal
      v-model:open="studentsModalVisible"
      title="班级学生列表"
      width="800px"
      :footer="null"
    >
      <div style="margin-bottom: 16px">
        <a-input-search
          v-model:value="studentSearchText"
          placeholder="搜索学生姓名"
          style="width: 200px"
          @search="handleStudentSearch"
        />
        <a-button
          type="primary"
          style="margin-left: 10px"
          @click="showAddStudentsModal"
          v-checkpermission:foo.bar="'class_edit'"
        >
          <template #icon><plus-outlined /></template>
          添加学生
        </a-button>
      </div>

      <a-table
        :dataSource="studentsData"
        :columns="studentColumns"
        :pagination="studentPagination"
        @change="handleStudentTableChange"
        :loading="studentsLoading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-button
              type="text"
              danger
              size="small"
              @click="removeStudent(record.id)"
              v-checkpermission:foo.bar="'class_edit'"
            >
              移除
            </a-button>
          </template>
        </template>
      </a-table>
    </a-modal>

    <!-- 添加学生对话框 -->
    <a-modal
      v-model:open="addStudentsModalVisible"
      title="添加学生(未分配班级)到班级"
      @ok="handleAddStudentsOk"
      width="800px"
    >
      <div style="margin-bottom: 16px">
        <a-input-search
          v-model:value="studentSelectSearchText"
          placeholder="搜索学生姓名"
          style="width: 200px"
          @search="handleStudentSelectSearch"
        />
      </div>

      <a-table
        :dataSource="availableStudentsData"
        :columns="studentSelectColumns"
        :pagination="studentSelectPagination"
        @change="handleStudentSelectTableChange"
        :loading="availableStudentsLoading"
        :row-selection="{
          selectedRowKeys: selectedStudentKeys,
          onChange: onStudentSelectChange,
        }"
      >
      </a-table>
    </a-modal>

    <!-- 添加设置老师对话框 -->
    <a-modal
      v-model:open="setTeacherModalVisible"
      title="设置班级老师"
      @ok="handleSetTeacherOk"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="选择老师">
          <a-select
            v-model:value="selectedTeacherId"
            placeholder="请选择老师"
            show-search
            option-filter-prop="label"
            :filter-option="filterTeacherOption"
          >
            <a-select-option
              v-for="teacher in availableTeachers"
              :key="teacher.id"
              :value="teacher.id"
              :label="teacher.truename"
            >
              {{ teacher.truename }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
  
  <script lang="ts" setup>
import XSearch from "./XSearch.vue";
import type { TableProps } from "ant-design-vue";
import { ref, onMounted, reactive, computed, toRaw, createVNode } from "vue";
import http from "../routerutils/http";
import type { Rule } from "ant-design-vue/es/form";
import type { UnwrapRef } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { useStore } from "vuex";
import dayjs from "dayjs";

const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
console.log("当前用户的权限：：", userPermiss_vuex);
// 权限指令
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      el.parentNode?.removeChild(el);
    }
  },
};

// 搜索相关
const name = ref<string>("");
const program_id = ref<number>();
const status = ref<string>();
const allPrograms = ref<any[]>([]);

// 重置搜索
const reset_search = () => {
  state.current = 1;
  name.value = "";
  program_id.value = undefined;
  status.value = undefined;
  getClassList();
};

// 搜索按钮
const but_search = () => {
  state.current = 1;
  getClassList();
};

// 获取所有专业
const getAllPrograms = async () => {
  try {
    const response = await http.get("/api/classes/programs/list");
    allPrograms.value = response.data.data;
  } catch (error) {
    console.log("获取专业列表失败:", error);
    message.error("获取专业列表失败");
  }
};

// 新增添加老师的弹窗
interface availableTeachers {
    id:number;
    truename:string
}
const setTeacherModalVisible = ref<boolean>(false);
const selectedTeacherId = ref();
const availableTeachers = ref<availableTeachers[]>([]);
const currentClassForTeacher = ref<number>()
// 弹出框
const showModal_set = (record:any) => {
    console.log("当前老师的id：",record)
    setTeacherModalVisible.value = true
    currentClassForTeacher.value = record.id
    selectedTeacherId.value = record.teacher_id
    // teacher_id
    getteacher_list()
}

// 获取所以的老师列表
const getteacher_list = async () => {
  try {
    const res = await http.get("/api/users/teacher_list");
    availableTeachers.value = res.data.results;
  } catch (error) {
    console.log("报错了：", error);
  }
};

// 设置老师确认
const handleSetTeacherOk = async () => {
  if (!selectedTeacherId.value || !currentClassForTeacher.value) {
    message.warning("请选择老师");
    return;
  }

  try {
    const response = await http.post("/api/classes/setTeacher", {
      class_id: currentClassForTeacher.value,
      teacher_id: selectedTeacherId.value,
    });
    
    message.success(response.data.msg);
    setTeacherModalVisible.value = false;
    selectedTeacherId.value = undefined;
    // 刷新班级列表
    getClassList();
  } catch (error) {
    console.log("设置老师失败:", error);
    message.error("设置老师失败");
  }
};

// 老师搜索筛选
const filterTeacherOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 表格相关
const loading = ref<boolean>(false);
const columns = [
  {
    title: "班级名称",
    dataIndex: "name",
    key: "name",
    width: 150,
  },
  {
    title: "班级编号",
    dataIndex: "class_id",
    key: "class_id",
    width: 100,
  },
  {
    title: "所属专业",
    dataIndex: "program_name",
    key: "program_name",
    width: 150,
  },
  {
    title: "班级老师",
    dataIndex: "teacher_name",
    key: "teacher_name",
    width: 150,
  },
  {
    title: "学生人数",
    dataIndex: "student_count",
    key: "student_count",
    width: 80,
  },
  {
    title: "状态",
    dataIndex: "state",
    key: "state",
    width: 80,
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    key: "created_at",
    width: 160,
  },
  {
    title: "操作",
    key: "action",
    width: 300,
  },
];

const dataSource = ref<any[]>([]);
const state = reactive({
  selectedRowKeys: [] as any[],
  loading: false,
  pageSize: 10,
  total: 0,
  current: 1,
});

// 获取班级列表
const getClassList = async () => {
  try {
    loading.value = true;
    const response = await http.get("/api/classes", {
      params: {
        name: name.value.trim(),
        program_id: program_id.value,
        status: status.value,
        page_size: state.pageSize,
        page: state.current,
      },
    });
    console.log(response.data);
    dataSource.value = response.data.data.list.map((item: any) => ({
      ...item,
      created_at:dayjs(item.created_at).format("YYYY-MM-DD HH:mm:ss"),
      key: item.id,
    }));
    state.total = response.data.data.total;
  } catch (error) {
    console.log("获取班级列表失败:", error);
    message.error("获取班级列表失败");
  } finally {
    loading.value = false;
  }
};

// 表格分页变化
const handleTableChange = (pagination: any) => {
  state.pageSize = pagination.pageSize;
  state.current = pagination.current;
  getClassList();
};

// 新增班级相关
const open = ref<boolean>(false);
const formRef = ref();
const labelCol = { span: 5 };
const wrapperCol = { span: 13 };

interface FormState {
  name: string;
  class_id: string;
  program_id: number | undefined;
}

const formState: UnwrapRef<FormState> = reactive({
  name: "",
  class_id: "",
  program_id: undefined,
});

const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: "请输入班级名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度为2到20个字符", trigger: "blur" },
  ],
  class_id: [
    { required: true, message: "请输入班级编号", trigger: "blur" },
    { min: 2, max: 20, message: "长度为2到20个字符", trigger: "blur" },
  ],
  program_id: [
    { required: true, message: "请选择所属专业", trigger: "change" },
  ],
};

const showModal = () => {
  open.value = true;
};

const handleOk = () => {
  formRef.value
    .validate()
    .then(async () => {
      try {
        const response = await http.post("/api/classes/add", {
          name: formState.name,
          class_id: formState.class_id,
          program_id: formState.program_id,
        });

        message.success(response.data.msg);
        open.value = false;
        // 重置表单
        formRef.value.resetFields();
        // 刷新列表
        getClassList();
      } catch (error) {
        console.log("添加班级失败:", error);
      }
    })
    .catch((error: any) => {
      console.log("表单验证失败:", error);
    });
};

// 编辑班级相关
const open_edit = ref<boolean>(false);
const formRef_edit = ref();
const formState_edit: UnwrapRef<FormState> = reactive({
  name: "",
  class_id: "",
  program_id: undefined,
});

const showModal_edit = async (id: number) => {
  try {
    const response = await http.get(`/api/classes/get/${id}`);
    const classInfo = response.data.data;

    formState_edit.name = classInfo.name;
    formState_edit.class_id = classInfo.class_id;
    formState_edit.program_id = classInfo.program_id;

    open_edit.value = true;
  } catch (error) {
    console.log("获取班级详情失败:", error);
    message.error("获取班级详情失败");
  }
};

const handleOk_edit = () => {
  formRef_edit.value
    .validate()
    .then(async () => {
      try {
        const response = await http.put(
          `/api/classes/update/${formState_edit.id}`,
          {
            name: formState_edit.name,
            class_id: formState_edit.class_id,
            program_id: formState_edit.program_id,
          }
        );

        message.success(response.data.msg);
        open_edit.value = false;
        // 刷新列表
        getClassList();
      } catch (error) {
        console.log("更新班级失败:", error);
      }
    })
    .catch((error: any) => {
      console.log("表单验证失败:", error);
    });
};

// 禁用班级
const disableClass = (id: number) => {
  Modal.confirm({
    title: "禁用班级",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要禁用此班级吗？禁用后该班级将不再可用。",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        const response = await http.put(`/api/classes/${id}/disable`);
        message.success(response.data.msg);
        getClassList();
      } catch (error) {
        console.log("禁用班级失败:", error);
        message.error("禁用班级失败");
      }
    },
  });
};

// 启用班级
const enableClass = (id: number) => {
  Modal.confirm({
    title: "启用班级",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要启用此班级吗？",
    okText: "确定",
    okType: "primary",
    cancelText: "取消",
    async onOk() {
      try {
        const response = await http.put(`/api/classes/${id}/enable`);
        message.success(response.data.msg);
        getClassList();
      } catch (error) {
        console.log("启用班级失败:", error);
        message.error("启用班级失败");
      }
    },
  });
};

// 删除班级
const deleteClass = (id: number) => {
  Modal.confirm({
    title: "删除班级",
    icon: createVNode(ExclamationCircleOutlined),
    content: "慎重: 此操作不可退回。您确定要删除此班级吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        const response = await http.delete(`/api/classes/${id}`);
        message.success(response.data.msg);
        getClassList();
      } catch (error) {
        console.log("删除班级失败:", error);
        message.error("删除班级失败");
      }
    },
  });
};

// 班级学生列表相关
const studentsModalVisible = ref(false);
const currentClassId = ref<number>();
const studentsData = ref<any[]>([]);
const studentsLoading = ref(false);
const studentSearchText = ref("");
const studentPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const studentColumns = [
  {
    title: "ID",
    dataIndex: "id",
    key: "id",
  },
  {
    title: "学号",
    dataIndex: "student_id",
    key: "student_id",
  },
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "性别",
    dataIndex: "gender",
    key: "gender",
  },
  {
    title: "邮箱",
    dataIndex: "email",
    key: "email",
  },
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone",
  },
  {
    title: "操作",
    key: "action",
    width: 80,
  },
];

const showStudentsModal = async (classId: number) => {
  currentClassId.value = classId;
  studentsModalVisible.value = true;
  await getClassStudents();
};

const getClassStudents = async () => {
  if (!currentClassId.value) return;

  try {
    studentsLoading.value = true;
    const response = await http.get(
      `/api/classes/${currentClassId.value}/students`,
      {
        params: {
          page: studentPagination.current,
          page_size: studentPagination.pageSize,
          search: studentSearchText.value,
        },
      }
    );

    studentsData.value = response.data.data.map((item: any) => ({
      ...item,
      key: item.id,
    }));
    studentPagination.total = response.data.total || 0;
  } catch (error) {
    console.log("获取班级学生列表失败:", error);
    message.error("获取班级学生列表失败");
  } finally {
    studentsLoading.value = false;
  }
};

const handleStudentTableChange = (pagination: any) => {
  studentPagination.current = pagination.current;
  studentPagination.pageSize = pagination.pageSize;
  getClassStudents();
};

const handleStudentSearch = () => {
  studentPagination.current = 1;
  getClassStudents();
};

// 移除学生
const removeStudent = async (studentId: number) => {
  Modal.confirm({
    title: "移除学生",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要将此学生从班级中移除吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        const response = await http.delete(
          `/api/classes/${currentClassId.value}/students/${studentId}`
        );
        message.success(response.data.msg);
        getClassStudents();
      } catch (error) {
        console.log("移除学生失败:", error);
        message.error("移除学生失败");
      }
    },
  });
};

// 添加学生相关
const addStudentsModalVisible = ref(false);
const availableStudentsData = ref<any[]>([]);
const availableStudentsLoading = ref(false);
const selectedStudentKeys = ref<number[]>([]);
const studentSelectSearchText = ref("");
const studentSelectPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const studentSelectColumns = [
  {
    title: "学号",
    dataIndex: "student_id",
    key: "student_id",
  },
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "邮箱",
    dataIndex: "email",
    key: "email",
  },
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone",
  },
];

const showAddStudentsModal = async () => {
  addStudentsModalVisible.value = true;
  selectedStudentKeys.value = [];
  await getAvailableStudents();
};

const getAvailableStudents = async () => {
  try {
    availableStudentsLoading.value = true;
    /*
    name, 
            class_id, 
            student_id,
            gender,
    */
    const response = await http.get("/api/classes/students", {
      params: {
        name: studentSelectSearchText.value.trim(),
        page: studentSelectPagination.current,
        page_size: studentSelectPagination.pageSize,
      },
    });

    availableStudentsData.value = response.data.data.list.map((item: any) => ({
      ...item,
      key: item.id,
    }));
    studentSelectPagination.total = response.data.data.total || 0;
  } catch (error) {
    console.log("获取可添加学生列表失败:", error);
    message.error("获取可添加学生列表失败");
  } finally {
    availableStudentsLoading.value = false;
  }
};

const handleStudentSelectTableChange = (pagination: any) => {
  studentSelectPagination.current = pagination.current;
  studentSelectPagination.pageSize = pagination.pageSize;
  getAvailableStudents();
};

const handleStudentSelectSearch = () => {
  studentSelectPagination.current = 1;
  getAvailableStudents();
};

const onStudentSelectChange = (selectedKeys: number[]) => {
  selectedStudentKeys.value = selectedKeys;
};

const handleAddStudentsOk = async () => {
  if (selectedStudentKeys.value.length === 0) {
    message.warning("请至少选择一名学生");
    return;
  }

  try {
    const response = await http.post(
      `/api/classes/${currentClassId.value}/students`,
      {
        student_ids: selectedStudentKeys.value,
      }
    );

    message.success(response.data.msg);
    addStudentsModalVisible.value = false;
    // 刷新学生列表
    getClassStudents();
  } catch (error) {
    console.log("添加学生失败:", error);
    message.error("添加学生失败");
  }
};

// 初始化
onMounted(() => {
  getClassList();
  getAllPrograms();
});
</script>
  
  <style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
</style>